package cn.xinfei.xdecision.datasource.mongodb;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.mongo.MongoProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.SimpleMongoClientDatabaseFactory;
import org.springframework.data.mongodb.core.convert.MappingMongoConverter;
import org.springframework.data.mongodb.core.convert.MongoCustomConversions;
import org.springframework.data.mongodb.repository.config.EnableMongoRepositories;

/**
 * @author xiaomifeng1010
 * @version 1.0
 * @date: 2022/6/23 18:39
 * @Description 本系统mongodb数据源配置
 */
@Configuration
@ConditionalOnProperty( name = "spring.data.mongo.exam.enable")
@EnableMongoRepositories(mongoTemplateRef = "examMongoTemplate")
public class DataMongoTemplate {


    @Bean(name = "examMongoProperties")
    @ConfigurationProperties(prefix = "spring.data.mongo.exam")
    @ConditionalOnProperty( name = "spring.data.mongo.exam.enable")
    public MongoProperties examMongoProperties() {
        return new MongoProperties();
    }

    @Bean(name = "examMongoTemplate")
    @ConditionalOnProperty( name = "spring.data.mongo.exam.enable")
    public MongoTemplate examMongoTemplate(@Qualifier("examMongoProperties") MongoProperties examMongoProperties, @Qualifier("mongoCustomConversions") MongoCustomConversions mongoCustomConversions) {
        MongoTemplate mongoTemplate = new MongoTemplate(mongoDatabaseFactory(examMongoProperties));
        MappingMongoConverter mongoMapping = (MappingMongoConverter) mongoTemplate.getConverter();
        mongoMapping.setCustomConversions(mongoCustomConversions);
        mongoMapping.afterPropertiesSet();

        return mongoTemplate;
    }


    @Bean(name = "examMongoFactory")
    @ConditionalOnProperty( name = "spring.data.mongo.exam.enable")
    public MongoDatabaseFactory mongoDatabaseFactory(@Qualifier("examMongoProperties") MongoProperties examMongoProperties) {
        return new SimpleMongoClientDatabaseFactory(examMongoProperties.getUri());
    }

}